#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>

// 打印今日天气
void print_today_weather(const char *response, size_t size) {
    // 解析 JSON 响应
    cJSON *json = cJSON_ParseWithLength(response, size);
    if (json == NULL) {
        fprintf(stderr, "解析 JSON 失败: [%s]\n", cJSON_GetErrorPtr());
        return;
    }

    // 获取 "data" 对象
    cJSON *data = cJSON_GetObjectItemCaseSensitive(json, "data");
    if (!cJSON_IsObject(data)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'data' 对象\n");
        cJSON_Delete(json);
        return;
    }

    // 获取 "weatherData" 对象
    cJSON *weatherData = cJSON_GetObjectItemCaseSensitive(data, "weatherData");
    if (!cJSON_IsObject(weatherData)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'weatherData' 对象\n");
        cJSON_Delete(json);
        return;
    }

    // 获取天气数据字段
    cJSON *temperature = cJSON_GetObjectItemCaseSensitive(weatherData, "temperature");
    cJSON *weather = cJSON_GetObjectItemCaseSensitive(weatherData, "weather");
    cJSON *humidity = cJSON_GetObjectItemCaseSensitive(weatherData, "humidity");

    if (!cJSON_IsNumber(temperature) || !cJSON_IsString(weather) || !cJSON_IsNumber(humidity)) {
        fprintf(stderr, "JSON 格式错误: 找不到必要的天气信息\n");
        cJSON_Delete(json);
        return;
    }

    // 打印今日天气
    printf("今日天气：\n");
    printf("温度：%.1f °C\n", cJSON_GetNumberValue(temperature));
    printf("天气：%s\n", weather->valuestring);
    printf("湿度：%.1f%%\n", cJSON_GetNumberValue(humidity));

    // 释放 JSON 对象
    cJSON_Delete(json);
}

int main(void) {
    CURL *client;
    CURLcode err;
    char *response;
    size_t size;

    // 创建内存流
    FILE *memstream = open_memstream(&response, &size);
    if (memstream == NULL) {
        perror("open_memstream");
        return 1;
    }

    // 初始化 CURL
    curl_global_init(CURL_GLOBAL_ALL);
    client = curl_easy_init();

    // 设置 CURL 选项
    curl_easy_setopt(client, CURLOPT_URL, "https://v2.jinrishici.com/info");
    curl_easy_setopt(client, CURLOPT_WRITEDATA, memstream);

    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "X-User-Token: tVgJ29i700dX3FnRPu8SgDoIv0HoQjOO");
    curl_easy_setopt(client, CURLOPT_HTTPHEADER, headers);

    // 执行 CURL 请求
    err = curl_easy_perform(client);
    fclose(memstream); // 关闭内存流

    if (err != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() 失败: %s\n", curl_easy_strerror(err));
    } else {
        // 打印今日天气
        print_today_weather(response, size);
    }

    // 清理资源
    curl_slist_free_all(headers);
    curl_easy_cleanup(client);
    free(response);
    curl_global_cleanup();

    return 0;
}
